﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BO;
using UIControls;

using BrightIdeasSoftware;
using System.Diagnostics;
using System.Collections;
using System.Data.Entity;

using UI.Core;
namespace UI
{
    public partial class TrxnListEditForm : EditFormBase, IMenuForm
    {
        public TrxnListEditForm()
        {
            InitializeComponent();
      
            MyGrid = grid;
        
            MyGrid.UseAlternatingBackColors = false;
            MyGrid.RowFormatter = new RowFormatterDelegate(ProcessRow);

            
        }

        private void ProcessRow(OLVListItem olvItem)
        {
            var obj = olvItem.RowObject as Billing;
            if (obj == null)
                return;
            MyGrid.HighlightForegroundColor = Color.Red;
      
            var staffName = obj.StaffName;
              var s=staffList.FirstOrDefault(item => item.Name == staffName);
                if (!string.IsNullOrWhiteSpace(staffName) &&  s== null)
                {

                   
                    olvItem.BackColor = Color.Red;
                    olvItem.ToolTipText = "aaaa";
                    olvItem.SubItems[2].ForeColor = Color.Red;
                }
            else if ( s!= null)
            {
                if (obj.CompanyName != s.CompanyName)
                {
                    olvItem.SubItems[6].ForeColor = Color.Red;
                }
                if (obj.CenterName != s.CenterName)
                {
                    olvItem.SubItems[6].ForeColor = Color.Red;
                }
                if (obj.DepartmentName != s.DepartmentName)
                {
                    olvItem.SubItems[6].ForeColor = Color.Red;
                }
            }
                olvItem.UseItemStyleForSubItems = false;
        }
        StaffList staffList;
        ProductList productList;
        BillingList mySource;

        protected DateTime BeginDate
        {
            get { return dateBegin.DateTimePicker.Value.Date; }
        }
        protected DateTime EndDate
        {
            get { return dateEnd.DateTimePicker.Value.Date; }
        }
        protected string companyName
        {
            get
            {
                if (cbCompany.ComboBox.SelectedValue == null)
                    return string.Empty;
                return cbCompany.ComboBox.SelectedValue.ToString();
            }
        }
        protected string centerName
        {
            get
            {
                if (cbCenter.ComboBox.SelectedValue == null)
                    return string.Empty;
                return cbCenter.ComboBox.SelectedValue.ToString();
            }
        }
        protected string departmentName
        {
            get
            {
                if (cbDepartment.ComboBox.SelectedValue == null)
                    return string.Empty;
                return cbDepartment.ComboBox.SelectedValue.ToString();
            }
        }
        protected string productName
        {
            get
            {
                if (cbProduct.ComboBox.SelectedValue == null)
                    return string.Empty;
                return cbProduct.ComboBox.SelectedValue.ToString();
            }
        }
        protected string productGroupName
        {
            get
            {
                if (cbProductGroup.ComboBox.SelectedValue == null)
                    return string.Empty;
                return cbProductGroup.ComboBox.SelectedValue.ToString();
            }
        }

        protected override void OnQuery()
        {
          
            BindFileds();
       
            FetchData();
            DataBind();
        }

        protected void FildChanged(object sender, EventArgs e)
        {
            NotifyForChange();
            base.FildChanged(sender, e);
        }

        void BindFileds()
        {
            var d1 = ListFactory<CompanyList>.GetList("")
                .Select(item=>item.Name).Distinct().ToList();
            d1.Insert(0,"");
            cbCompany.ComboBox.DataSource = d1;


            var d2 = ListFactory<DepartmentList>.GetList("").Select(item => item.Name).Distinct().ToList();
            d2.Insert(0, "");
            cbDepartment.ComboBox.DataSource = d2;
            //cbDepartment.ComboBox.ValueMember = "Name";
            //cbDepartment.ComboBox.DisplayMember = "Name";

            var d3 = ListFactory<ProductList>.GetList("").Select(item => item.Name).Distinct().ToList();
            d3.Insert(0, "");
            cbProduct.ComboBox.DataSource = d3;
            //cbProduct.ComboBox.ValueMember = "Name";
            //cbProduct.ComboBox.DisplayMember = "Name";

            var d4 = ListFactory<ProductGroupList>.GetList("").Select(item => item.Name).Distinct().ToList();
            d4.Insert(0, "");
            cbProductGroup.ComboBox.DataSource = d4;
            //cbProductGroup.ComboBox.ValueMember = "Name";
            //cbProductGroup.ComboBox.DisplayMember = "Name";

            var d5 = ListFactory<CenterList>.GetList("").Select(item => item.Name).Distinct().ToList();
            d5.Insert(0, "");
            cbCenter.ComboBox.DataSource = d5;
            //cbCenter.ComboBox.ValueMember = "Name";
            //cbCenter.ComboBox.DisplayMember = "Name";
        }

        private void Form_Load(object sender, EventArgs e)
        {
            BindFileds();
            var d = DateTime.Now;
            dateBegin.DateTimePicker.Value = new DateTime(d.Year, d.Month, 1);
            dateEnd.DateTimePicker.Value = d;

        
            OnSetGridColumns();
            InitGrid();
            OnQuery();
            MyGrid.RowObjectType = typeof(Billing);
            this.dateBegin.DateTimePicker.ValueChanged += new System.EventHandler(this.FildChanged);
            this.dateEnd.DateTimePicker.ValueChanged += new System.EventHandler(this.FildChanged);
            this.cbDepartment.ComboBox.SelectedValueChanged += new System.EventHandler(this.FildChanged);
            this.cbCompany.ComboBox.SelectedValueChanged += new System.EventHandler(this.FildChanged);
            this.cbCenter.ComboBox.SelectedValueChanged += new System.EventHandler(this.FildChanged);
            this.cbProductGroup.ComboBox.SelectedValueChanged += new System.EventHandler(this.FildChanged);
            this.cbProduct.ComboBox.SelectedValueChanged += new System.EventHandler(this.FildChanged);

        }
      
        protected override void FetchData()
        {

            mySource = ListFactory<BillingList>.GetList(string.Format(@"
CompanyName Like '%{0}%'
And CenterName Like '%{1}%'
And DepartmentName Like '%{2}%'
And ProductGroupName Like '%{3}%'
And ProductName Like '%{4}%'
And TransDate>='{5}'
And TransDate<='{6}'
And {7}
And HasDeleted=0
", companyName, centerName, departmentName, productGroupName, productName,BeginDate, EndDate,GlobalVar.User.CompanyFilter
),"TransDate desc,ID desc",0);

            staffList = AppContext.StaffList;
            productList = ListFactory<ProductList>.GetList("");
          

            GridDataSource = mySource;

       
        }
        protected override void DataBind()
        {
            base.DataBind();
            TotalAmt = mySource.Sum(item => item.Amount);
            RowCount = MyGrid.Items.Count;
        }

        void OnSetGridColumns()
        {
            var cols = new List<OLVColumn>();

            cols.Add(new OLVColumn("编号", "ID") { IsEditable = false, Width = 50 });
            var cDate = new OLVColumn(FieldHelper.cnName.Date, "TransDate");
            cDate.Width = 110;
            cDate.AspectToStringFormat = "{0:d}";
            cDate.ClusteringStrategy = new DateTimeClusteringStrategy(DateTimePortion.Day| DateTimePortion.Month| DateTimePortion.Year, "yyyy-MM-dd");
            cols.Add(cDate);
            cols.Add(new OLVColumn(FieldHelper.cnName.Staff, "StaffName") { Width = 60 });
            
           
       
            cols.Add(new OLVColumn(FieldHelper.cnName.Product, "ProductName") { Width = 150 });
            cols.Add(new OLVColumn(FieldHelper.cnName.Amount, "Amount") { Width = 80 });
            cols.Add(new OLVColumn(FieldHelper.cnName.ProductGroup, "ProductGroupName") { Width = 110 });


            cols.Add(new OLVColumn(FieldHelper.cnName.Company, "CompanyName") { Width = 60, IsEditable = GlobalVar.User.AllowAllCompany });
            cols.Add(new OLVColumn(FieldHelper.cnName.Center, "CenterName") { Width = 60 });
            cols.Add(new OLVColumn(FieldHelper.cnName.Department, "DepartmentName") { Width = 60 });
         
           
            cols.Add(
                new OLVColumn(FieldHelper.cnName.IsNewCustomer, "IsNewCustomer")
                {
                    Width = 60,
                    AspectToStringConverter =
                    new AspectToStringConverterDelegate(item => (bool)item == true ? "是" : "否")
                }
             );
            cols.Add(new OLVColumn("门票家数", "MenPiaoCount") { Width = 40 });
            cols.Add(new OLVColumn("讲师姓名", "TeacherName") { Width = 80 });
            cols.Add(new OLVColumn("渠道", "Channel") { Width = 80 });
            cols.Add(new OLVColumn("合同单号", "ContractNo") { Width = 100 });
            cols.Add(new OLVColumn(FieldHelper.cnName.CRM_OrderNo, "CRM_OrderNo") { Width = 100 });

            cols.Add(new OLVColumn(FieldHelper.cnName.Customer, "CustomerName") { Width = 250, WordWrap=true });
            cols.Add(new OLVColumn(FieldHelper.cnName.Remark, "Remark") { Width = 250 });

            cols.Add(new OLVColumn("创建人", "Operator") { Width = 100, IsEditable = false });
            cols.Add(new OLVColumn("创建时间", "CreateTime")
            {
                Width = 100,
                IsEditable = false,
                AspectToStringFormat = "{0:d}" 
                ,ClusteringStrategy = new DateTimeClusteringStrategy(DateTimePortion.Day| DateTimePortion.Month| DateTimePortion.Year, "yyyy-MM-dd")
            });
            cols.Add(new OLVColumn("最后修改人", "Operator") { Width = 100, IsEditable = false });
            cols.Add(new OLVColumn("最后修改时间", "CreateTime")
            {
                Width = 100,
                IsEditable = false,
                AspectToStringFormat = "{0:d}"
                ,
                ClusteringStrategy = new DateTimeClusteringStrategy(DateTimePortion.Day | DateTimePortion.Month | DateTimePortion.Year, "yyyy-MM-dd")
            });
        
            MyGrid.Columns.AddRange(cols.ToArray());

        }
        protected override void OnGridFilterd(UIControls.Grid.OSGrid.FilterdEventArgs e)
        {
            double t = 0;
            long cnt=0;
            foreach (Billing item in e.FilteredObjects)
            {
                t += item.Amount;
                cnt++;
            }
            TotalAmt = t;
            RowCount = cnt;
        }

    

        protected override object OnAdd()
        {

            var obj = new Billing();
            if (GlobalVar.User.AllowAllCompany)
                obj.CompanyName = companyName;
            else
                obj.CompanyName = GlobalVar.User.CompanyName;
            obj.CenterName = centerName;
            obj.DepartmentName = departmentName;

            obj.ProductGroupName = productGroupName;
            obj.ProductName = productName;

            obj.TransDate = EndDate;

            obj.CreateTime = DateTime.Now;
            obj.LastModifyTime = DateTime.Now;

            obj.Operator = GlobalVar.User.UserName;
            obj.LastOprator = GlobalVar.User.UserName;

            return obj;

        }


        protected override void OnSave()
        {
            try
            {
                foreach (Billing delObj in RemovedList)
                {
                    if (delObj == null)
                        continue;
                    if (delObj.ID == 0)
                        continue;
                   // mySource.Remove (delObj);
                    delObj.HasDeleted = true;
                }
                RemovedList.Clear();

                foreach (Billing obj in MyGrid.Objects)
                {
                    if (obj == null)
                        continue;
                    if (obj.ID == 0)
                        mySource.Add(obj);
                   
                }

                mySource.Save();
         
                FetchData();
                DataBind();
            }
            catch (ExceptionEx exp)
            {
                ExcptionHandler.ShowExcption(exp);
            }

        }
        void ProcessColumnCustomerName(CellEditEventArgs e)
        {
            var obj = e.RowObject as Billing;
            var customerName = e.NewValue.ToString();
            var q = from item in mySource
                    where item.CustomerName == customerName
                    orderby item.TransDate descending, item.CreateTime descending
                    select item;
            if (q.Count() == 0)
            {
                obj.IsNewCustomer = true;
            }
            else
            {
                var orignalObj = q.FirstOrDefault();
                if (orignalObj.TransDate.Year < DateTime.Now.Year)
                {
                    obj.IsNewCustomer = false;
                }
                else
                    obj.IsNewCustomer = orignalObj.IsNewCustomer;
            }
        }
        void ProcessColumnStaffName(CellEditEventArgs e)
        {
            var obj = e.RowObject as Billing;
            var staffName = e.NewValue.ToString();
            var q = (from item in staffList
                     where item.Name == staffName
                     select item).FirstOrDefault();
            if (q == null)
            {
              
                return;
            }
            else
            {
               
                obj.CompanyName = q.CompanyName;
                obj.CenterName = q.CenterName;
                obj.DepartmentName = q.DepartmentName;
            }
        }
        void ProcessColumnProductName(CellEditEventArgs e)
        {
            var obj = e.RowObject as Billing;
            var staffName = e.NewValue.ToString();
            var q = (from item in productList
                     where item.Name == staffName
                     select item).FirstOrDefault();
            if (q == null)
                return;

            obj.ProductGroupName = q.ProductGroupName;
            obj.Amount = q.Price;
        }
        protected override void OnCellEditFinishing(CellEditEventArgs e)
        {
            switch (e.Column.AspectName)
            {
                case "CustomerName":
                    ProcessColumnCustomerName(e);
                    break;
                case "StaffName":
                    ProcessColumnStaffName(e);
                    break;
                case "ProductName":
                    ProcessColumnProductName(e);
                    break;
            }
        }


       
    }
}
